﻿using System;
using System.Collections.Generic;
using CodeGenerator.interfaces;

namespace CodeGenerator.Implementations
{
    public class GeneratorClass : MultipleTargetObject, IGeneratorClass
    {
        private string _className = "";
        private IDataBaseTable _databaseTable;
        private string _sourceCode ="";
        public GeneratorClass(string Name, IDataBaseTable DataBaseTable)
        {
            _className = Name;
            _databaseTable = DataBaseTable;
            if (String.IsNullOrEmpty(Name))
                _className = _databaseTable.TableName;
        }

        public string ClassName
        {
            get { return _className; }
            //set { _className = value; }
        }

        public IDataBaseTable DatabaseTable
        {
            get { return _databaseTable; }
        }



       public IList<IProperty> Properties
        {
            get{
                List<IProperty> result = new List<IProperty>();
                
                foreach (var databaseColumn in _databaseTable.Columns)
                {
                    Property p = new Property(databaseColumn.ColumnName, databaseColumn, _databaseTable);
                    result.Add(p);
                }
            return result;
            }
        }

    

        public IList<IConstructor> Constructors
        {
            get { 
                List<IConstructor> result = new List<IConstructor>();
                if (_databaseTable.PrimaryKey != null && _databaseTable.PrimaryKey.Count >0)
                    result.Add(new Constructor(_databaseTable.TableName, _databaseTable.PrimaryKey));
                foreach (var uIndex in _databaseTable.UniqueIndexes)
                {
                    if(!AlreadyExists(result, uIndex))
                    result.Add(new Constructor(_databaseTable.TableName,uIndex.Columns));
                }
                return result;
            }
            
        }

 


        private bool AlreadyExists(List<IConstructor> List, IUniqueConstraint itemToCheck)
        {
            foreach (IConstructor constructor in List)
            {
                if (constructor.Columns.Count != itemToCheck.Columns.Count)
                    return false;
                if(constructor.GetSignatureHash == itemToCheck.GetSignatureHash)
                    return true;
            }
            return false;
        }

    }
}